package cn.yfj.org.controller;

import cn.yfj.basic.annotation.Log;
import cn.yfj.basic.util.AjaxResult;
import cn.yfj.basic.util.PageList;
import cn.yfj.org.domain.Department;
import cn.yfj.org.query.DeptmentQuery;
import cn.yfj.org.service.IDepartmentServiceI;
import cn.yfj.system.anno.PreAuthorize;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController //返回json格式
@RequestMapping("/dept") /*访问路径*/
@Api(tags = "部门接口", description = "部门接口详细描述")
public class DepartmentController {

    @Autowired /*依赖注入*/
    private IDepartmentServiceI service;

    /*查询全部*/
    @GetMapping /*访问路径使用get请求访问*/
    @Log(value = "部门查询所有")
    public List<Department> queryAll() {
        return service.queryAll();
    }

    /*查询单条*/
    @GetMapping("/{id}") /*使用post请求并且传入id*/
    public Department queryById(@PathVariable("id") Long id) {
        return service.queryById(id);
    }

    /*分页加高级查询*/
    @PostMapping() /*设置路径使用post访问*/
    @Log(value = "部门分页和高级查询")
    @PreAuthorize(value ="department:list",name = "部门列表")
    public PageList<Department> queryPage(@RequestBody DeptmentQuery deptmentQuery) {
        return service.queryPage(deptmentQuery);
    }

    /*删除*/
    @DeleteMapping("/{id}")
    @Log(value = "部门删除")
    public AjaxResult remove(@PathVariable("id") Long id) {
        try {
            service.remove(id);
            /*操作成功直接返回*/
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            //操作失败返回false加失败
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    @PatchMapping()/*批量删除*/
    @Log(value = "部门批量删除")
    public AjaxResult bach(@RequestBody List<Long> ids) {
        try {
            service.bach(ids);
            /*操作成功直接返回*/
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            //操作失败返回false加失败
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    /*添加和修改*/
    @PutMapping /*设置路径，只用普通请求*/
    @Log(value = "部门增加和修改")  //这里添加了AOP的自定义注
    public AjaxResult saveOrUpdate(@RequestBody Department department) {
        try {
            if (department.getId() == null) {
                service.save(department);
            } else {
                service.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            //操作失败返回false加失败
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }


    }
    @GetMapping("/tree")
    @Log(value = "查询部门树")
    public List<Department> queryTree(){
        return service.queryTree();
    }
}
